from functools import wraps


def log_action(name: str, log_params: bool = False):
    """
    功能名称注解装饰器
    用法：@log_action("用户管理-创建用户")
    方法视图：@log_action("用户管理-查询用户列表")
    类视图：@log_action_for_class("订单管理-创建订单")
    log_params 自定义字段
    """

    def decorator(view_func):
        @wraps(view_func)
        def wrapped_view(request, *args, **kwargs):
            # 将功能名称存储在 request 对象中
            request.log_meta = {
                'action_name': name,
                'view_func': view_func.__name__,
                'view_args': log_params
            }
            return view_func(request, *args, **kwargs)

        return wrapped_view

    return decorator


# 类视图装饰器适配
def log_action_for_class(name: str, log_params: bool = False):
    """用于类视图的装饰器"""

    def decorator(cls):
        original_dispatch = cls.dispatch

        @wraps(original_dispatch)
        def wrapped_dispatch(request, *args, **kwargs):
            request.log_meta = {
                'action_name': name,
                'view_class': cls.__name__,
                'log_params': log_params
            }
            return original_dispatch(request, *args, **kwargs)

        cls.dispatch = wrapped_dispatch
        return cls

    return decorator
